<template>
  <div class="mainContainer">
    <Aside :visible="visible" @toggleAside="toggle" @scroll="scroll" />

    <div class="mainBody">
      <Header @toggleAside="toggle" />

      <div class="routerBody" id="routerBody">
        <router-view></router-view>
        <Footer />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onBeforeMount, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import {
  useLoginStore,
  useThemeStore,
  useProjectStore,
  useUserInfoStore,
  useOnlineStatusStore,
  useEnduringSseStore,
} from '@/features/store/store'
import Header from '@/components/Header/Header.vue'
import Aside from '@/components/Aside.vue'
import Footer from '@/components/Footer.vue'

// 侧边栏显示情况
const visible = ref<string>('mini')
// 切换侧边栏显示情况
const toggle = () => {
  if (visible.value === 'open') visible.value = 'mini'
  else visible.value = 'open'
}
// 滚动窗口到顶部
const scroll = () => {
  const win = document.getElementById('routerBody')
  win.scrollTo({ top: 0, behavior: 'smooth' })
}
const { status } = storeToRefs(useLoginStore())
watch(
  () => status.value,
  (newVal) => {
    if (newVal) visible.value = 'open'
    else visible.value = 'mini'
  }
)

//
//
// 初始化的一些配置
onBeforeMount(() => {
  // 初始化一下主题颜色
  useThemeStore().setTheme('theme-default')
  // 初始化一下用户信息
  useUserInfoStore().getUserInfo()
  // 初始化一下项目列表
  useProjectStore().getProjectList()
  // 登录时建立 SSE 持久连接
  useEnduringSseStore().connectEnduringSSE()
  setTimeout(() => {
    // 登录时检查一下未读消息
    useEnduringSseStore().getNotReadMessageCount()
  }, 1000)
})

//
//
// 联网相关
const { refresh } = storeToRefs(useOnlineStatusStore())
const { setStatus, setRefresh } = useOnlineStatusStore()
watch(
  () => refresh.value,
  () => ElMessage.error('网络未连接，无法获取远程连接和数据！')
)
// 1、监听网络连接
window.addEventListener('online', () => {
  // alert('有网') //重连SSE
  setStatus(true)
  useEnduringSseStore().connectEnduringSSE()
  useEnduringSseStore().getNotReadMessageCount()
})
// 2、监听网络断开
window.addEventListener('offline', () => {
  // alert('断网')
  setStatus(false)
  setRefresh()
})
</script>

<style scoped lang="less">
.mainContainer {
  width: 100vw;
  height: 100vh;
  display: flex;
  background-color: var(--theme-background);

  > .mainBody {
    flex: 1;
    height: 100%;

    > .routerBody {
      width: 100%;
      height: calc(100% - 54px);
      overflow: auto;
    }
  }
}
</style>
